<!-- src/components/TabsBar.vue -->
<template>
  <q-tabs
    v-model="activeTabPath"
    inline-label
    dense
    outside-arrows
    mobile-arrows
    @update:model-value="handleTabClick"
  >
    <q-tab
      v-for="tab in tabs"
      :key="tab.path"
      :name="tab.path"
      :icon="tab.icon"
      :label="tab.title"
      no-caps
    >
      <q-icon
        v-if="tab.closable"
        name="close"
        size="15px"
        color="primary"
        class="q-ml-sm cursor-pointer bg-white"
        @click.stop="handleCloseTab(tab.path)"
      />
    </q-tab>
  </q-tabs>
</template>

<script setup lang="ts">
import { useRouter } from 'vue-router'
import { storeToRefs } from 'pinia'
import { useTabsStore } from 'src/stores/tabsStore'

defineOptions({
  name: 'TabsBar',
})

const router = useRouter()
const tabsStore = useTabsStore()

// 使用 storeToRefs 保持响应性
const { tabs, activeTabPath } = storeToRefs(tabsStore)

// 点击标签页时跳转路由
const handleTabClick = (path: string) => router.push(path)

// 关闭标签页
const handleCloseTab = async (path: string) => {
  // 如果关闭的是当前页，则需要跳转到下一个激活页
  if (activeTabPath.value === path) {
    const index = tabs.value.findIndex((tab) => tab.path === path)
    const nextTab = tabs.value[index + 1] || tabs.value[index - 1]
    if (nextTab) await router.push(nextTab.path)
  }
  // 从 store 中移除
  tabsStore.removeTab(path)
}
</script>

<style lang="scss" scoped></style>
